home *** CD-ROM | disk | FTP | other *** search
- Path: anvil.ugrad.cs.ubc.ca!not-for-mail
- From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
- Newsgroups: comp.lang.c
- Subject: Re: String Problem
- Date: 25 Mar 1996 11:20:39 -0800
- Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
- Message-ID: <4j6rm7INNge5@anvil.ugrad.cs.ubc.ca>
- References: <4j6l61$4no@B1FF.mindspring.com>
- NNTP-Posting-Host: anvil.ugrad.cs.ubc.ca
-
- In article <4j6l61$4no@B1FF.mindspring.com>,
- Shon Frazier <vtipres@atl.mindspring.com> wrote:
- >This is supposed to be a variation on sample code from a textbook.
- >Can anyone tell me why NameCheck = 0 when I run the program?
- >
- >/*
- > Testing character transactions.
- >*/
- >
- >#include <stdio.h>
- >#include <ctype.h>
- >
- >int main()
- >{
- > char Name[11] = "John";
- > char *WhereName;
- > int NameCheck = 0;
- >
- > WhereName = Name;
- >
- > if ( WhereName == "John" )
- > {
- > NameCheck = 1;
- > }
- >
- > printf( "Name: %s\n", Name );
- > printf( "NameCheck = %i\n", NameCheck );
- > printf( "WhereName = %i\n", WhereName );
- >}
- >
- >
-
- NameCheck is zero after you run the program because the pointer WhereName does
- not coincide with the address of the string literal "John".
-
- You have pointed WhereName to be the address of the automatic object Name[0],
- that is, a pointer to the first element of Name.
-
- Then in your if statement, you compare this pointer against the string literal,
- which has a unique address distinct from Name, hence the comparison fails.
-
- You are comparing two character pointer values, not two strings.
-
- To compare the actual string data, include <string.h> and use the function
- called strcmp(). The == operator is not overloaded in C to compare strings.
- --
-
-